//package com.yueyang.sojourn.server.service.sojourn.pay;
//
//import com.alibaba.fastjson.JSON;
//import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
//import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
//import com.github.binarywang.wxpay.bean.profitsharing.*;
//import com.github.binarywang.wxpay.bean.request.WxPayOrderQueryRequest;
//import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
//import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
//import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
//import com.github.binarywang.wxpay.constant.WxPayConstants;
//import com.github.binarywang.wxpay.exception.WxPayException;
//import com.github.binarywang.wxpay.service.ProfitSharingService;
//import com.github.binarywang.wxpay.service.WxPayService;
//import com.yueyang.sojourn.server.model.enums.OrderStatusEnum;
//import com.yueyang.sojourn.server.model.po.SojournOrder;
//import com.yueyang.sojourn.server.model.po.SojournTransaction;
//import com.yueyang.sojourn.server.service.sojourn.order.SojournOrderService;
//import com.yueyang.sojourn.server.service.sojourn.transaction.SojournTransactionService;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.math.BigDecimal;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * 支付
// * @author Andy.yang
// * @version v1
// * @summary
// * @Copyright (c) 2019, YueYang Group All Rights Reserved.
// * @since 2020/3/25
// */
//@Service
//public class PayService {
//    @Autowired
//    WxPayService wxPayService;
//    @Autowired
//    ProfitSharingService profitSharingService;
//    @Autowired
//    SojournTransactionService transactionService;
//    @Autowired
//    SojournOrderService orderService;
//
//    /**
//     * 微信预支会订单
//     * 1: 必须保证幂等
//     *
//     * 本方法实现：
//     * 2：生成微信预支付订单（指明分账标识）
//     * 3：生成本地交易（残缺）
//     * 4：返回给小程序，让小程序进行直接对微信账号支付；
//     *
//     * 后续支付结果：
//     * 5：回调或主动查询（根据残缺交易）获取支付结果
//     * 6：补全 本地交易（残缺）、同步更新订单状态、同步库存
//     * @param orderId 本地订单
//     * @param openId 当前用户小程序中的Id
//     * @param needShare 是否需要分账
//     * @return 微信预支付id
//     */
//    public WxPayMpOrderResult prepay(String orderId,String openId,String ip,boolean needShare) {
//        BigDecimal price = new BigDecimal(0.1);
//        WxPayMpOrderResult result = null;
//        try {
//            //拼装微信预支付请求参数
//            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
//            orderRequest.setOutTradeNo(orderId);
////            orderRequest.setOpenid(openId);//服务商模式下，改为subOpenId
//            orderRequest.setSubOpenid(openId);
//            orderRequest.setBody("阅生活-上海9日游");
//            orderRequest.setProfitSharing(needShare ? "Y" : "N");//先打个标识，冻结支付：是否需要分账标识
//            orderRequest.setSubMchId("1581495641");//钱支付给子服务商
//            // 订单总金额：元转成分
//            int fee = 0;
//            BigDecimal actualPrice = price;
//            fee = actualPrice.multiply(new BigDecimal(100)).intValue();
//            orderRequest.setTotalFee(fee);
//            orderRequest.setSpbillCreateIp(ip);
//
//            result = wxPayService.createOrder(orderRequest);
//
//            //缓存prepayID用于后续模版通知
//            String prepayId = result.getPackageValue();
//            prepayId = prepayId.replace("prepay_id=", "");
//            //todo 支付日志
//            return result;
//        }catch (Exception e){
//            //todo 支付日志
//            return null;
//        }
//    }
//
//
//    public WxPayOrderQueryResult queryOrder(SojournTransaction transaction) {
//        BigDecimal price = new BigDecimal(0.1);
//        WxPayOrderQueryResult result = null;
//        try {
//            //拼装微信请求参数
//            WxPayOrderQueryRequest orderRequest = new WxPayOrderQueryRequest();
//            orderRequest.setOutTradeNo(transaction.getOrderSn());
//            orderRequest.setSubMchId("1581495641");//钱支付给子服务商: 这个子商户的订单
//
//            result = wxPayService.queryOrder(orderRequest);
//
//            if(!WxPayConstants.ResultCode.SUCCESS.equals(result.getResultCode())){
////                logger.error(xmlResult); todo 记录日志
//                throw new WxPayException("微信订单支付结果查询失败！");
//            }
//            if(!WxPayConstants.ResultCode.SUCCESS.equals(result.getReturnCode())){
////                logger.error(xmlResult); todo 记录日志
//                throw new WxPayException("微信订单支付结果查询失败！");
//            }
//            return result;
//            //todo 记录日志
//        }catch (Exception e){
//            //todo 记录日志
//            return null;
//        }
//    }
//
//    /**
//     * 商户管理中：只要新增一个商户就加入一个商户，至到成功
//     * 增加分账方:一次一个；预先设置，只有设置成功的，分账时指定的分账商户才可以分账；
//     *
//     * 没有查询成功的接口；所以只要没有设置成功，就不停的设置
//     */
//    public ProfitSharingReceiverResult addWxShareReceiver(String merchantId) throws WxPayException {
//        //1：查询项目所在分账方
//
//        //2：计算每个分账方具体分账金额
//
//        //3：设置微信分账方
////        ProfitSharingReceiverRequest receiverRequest = ProfitSharingReceiverRequest.newBuilder().build();
//        Receiver receiver = new Receiver(WxPayConstants.ReceiverType.MERCHANT_ID,
//                "1579764291",
//                "阅阳(上海)健康管理咨询有限公司",
//                "SERVICE_PROVIDER",
//                null);
//
//        ProfitSharingReceiverRequest receiverRequest = ProfitSharingReceiverRequest
//                .newBuilder()
//                .receiver(receiver.toJSONString())
//                .build();
//        receiverRequest.setSubMchId("1581495641");//当前分账方设置到此子商户号下
////        Map<String,Object> receiver = new HashMap();
//////        MERCHANT_ID：商户ID
//////        PERSONAL_WECHATID：个人微信号 PERSONAL_OPENID：个人openid（由父商户APPID转换得到）PERSONAL_SUB_OPENID: 个人sub_openid（由子商户APPID转换得到）
////
////        //服务商：
////        receiver.put("type","MERCHANT_ID");
////        receiver.put("name","阅阳(上海)健康管理咨询有限公司");
////        receiver.put("account","1579764291");
////        receiver.put("relation_type","SERVICE_PROVIDER");
////        receiverRequest.setReceiver(JSON.toJSONString(receiver));
//        ProfitSharingReceiverResult result = profitSharingService.addReceiver(receiverRequest);
//
//        if(!WxPayConstants.ResultCode.SUCCESS.equals(result.getResultCode())){
////                logger.error(xmlResult);
//            throw new WxPayException("微信增加分账账户失败！");
//        }
//        if(!WxPayConstants.ResultCode.SUCCESS.equals(result.getReturnCode())){
////                logger.error(xmlResult);
//            throw new WxPayException("微信增加分账账户失败！");
//        }
//        return result;
//    }
//
//
//    /**
//     * 开始单次分账
//     */
//    public ProfitSharingResult shareOne(String transId) throws WxPayException {
////        ProfitSharingRequest request = ProfitSharingRequest.newBuilder().build();
////        request.setOutOrderNo("one_" + transId);//分账单号
////        request.setTransactionId(transId);
//
//        ReceiverList instance = ReceiverList.getInstance();
//        instance.add(new Receiver(WxPayConstants.ReceiverType.MERCHANT_ID,
//                "1579764291",
//                3,
//                "制成"));
//        //30000002922019102310811092093
//        ProfitSharingRequest request = ProfitSharingRequest
//                .newBuilder()
//                .outOrderNo("one_" + transId)
//                .transactionId(transId)
//                .receivers(instance.toJSONString())
//                .build();
//        request.setSubMchId("1581495641");//当前分账方设置到此子商户号下
////
////        Map<String,Object> receiver = new HashMap();
//////        MERCHANT_ID：商户ID
//////        PERSONAL_WECHATID：个人微信号 PERSONAL_OPENID：个人openid（由父商户APPID转换得到）PERSONAL_SUB_OPENID: 个人sub_openid（由子商户APPID转换得到）
////
////        //服务商：
////        receiver.put("type","MERCHANT_ID");
////        receiver.put("name","阅阳(上海)健康管理咨询有限公司");
////        receiver.put("account","1579764291");
////        receiver.put("relation_type","SERVICE_PROVIDER");
////        request.setReceivers(JSON.toJSONString(receiver));
//
//        ProfitSharingResult result = profitSharingService.	profitSharing(request);
//        return result;
//    }
//
//    /**
//     * 结算分账
//     */
//    public ProfitSharingResult submitShare(String transId) throws WxPayException {
//        ProfitSharingFinishRequest request = ProfitSharingFinishRequest.newBuilder().build();
//        request.setOutOrderNo("finish_" + transId);//分账单号
//        request.setTransactionId(transId);
//        ProfitSharingResult result = profitSharingService.profitSharingFinish(request);
//        return result;
//    }
//
//    /**
//     * 分账结果
//     */
//    public ProfitSharingQueryResult queryFinish(String transId) throws WxPayException {
//        ProfitSharingQueryRequest request = ProfitSharingQueryRequest.newBuilder().build();
//        request.setOutOrderNo("finish_" + transId);//分账单号
//        request.setTransactionId(transId);
//        ProfitSharingQueryResult result = profitSharingService.profitSharingQuery(request);
//        return result;
//    }
//
//
//    /**
//     * 分账回退
//     */
//    public ProfitSharingReturnResult refundShare(String transId) throws WxPayException {
//        ProfitSharingReturnRequest request = ProfitSharingReturnRequest
//                .newBuilder()
//                .outOrderNo("one_" + transId)//本地的分账单号
//                .outReturnNo("one_rf_" + transId) //本地的回退单号
//                .returnAccountType("MERCHANT_ID")
//                .returnAccount("1579764291") //原接收方
//                .returnAmount(3)
//                .description("平台抽成退款")
//                .build();
//        request.setSubMchId("1581495641");//钱支付给子服务商
//
//
//        ProfitSharingReturnResult result = profitSharingService.profitSharingReturn(request);
//        return result;
//    }
//
//}
